Ext.define('cfWeb.cfWebComponent.AppHeadView', {
  extend: 'Ext.container.Container',
  alias: 'widget.appHeadView',
  layout: "border",
  height: 181,
  selfId: undefined,
  title: undefined,
  htmlTemp: '<div class="app_detail_head">' +
    '<div class="adh_logo" data-name="itemColor" style="color:#f00">' +
    '<div class="relatedApp" data-name="relatedApp"></div>' +
    '<img src="resources/img/icons/app1.png" height="90" width="180" data-name="itemImg" />' +
    '<span class="adh-icon adh_message_count" data-name="message"></span>' +
    '<p class="adh_title" data-name="title"></p>' +
    '</div>' +
    '<div class="add_detail_status">',
  htmlTemp2: '</div></div>',
  domainList: [],
  detailList: ['运行状态', '实例数量', '内存/硬盘', '运行环境', '服&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;务', '实例状态', '域&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名'],
  appData: null,
  actionList: {
    'add': '新建',
    'delete': '删除',
    'edit': '编辑',
    'save': '保存',
    'start': '启动',
    'stop': '停止',
    'restart': '重启',
    'loading': '载入中',
    'cancel': '取消'
  },
  isEditing: false,
  initComponent: function() {
    this.htmlInit();
    this.addEvents({
      //事件
      'onStatusChange': true,
      'onDomainChange': true,
      'relateClicked': true
    });
    this.callParent(arguments);
  },
  listeners: {
    boxready: function() {
      this.selfId = this.getEl().id;
      this.updateAppStatus(this.appData);
      this.eventBind();
    }
  },
  eventBind: function() {
    var buttons = Ext.select("div[id='" + this.selfId + "'] ul[data-name='action_status'] li");
    buttons.removeListener('click', this.appStatusChange, this);
    buttons.on('click', this.appStatusChange, this);

    var demains = Ext.select("div[id='" + this.selfId + "'] li.domain_item a.domain_text");
    demains.removeListener('click', this.domainClick, this);
    demains.on('click', this.domainClick, this);

    var dmButtons = Ext.select("div[id='" + this.selfId + "'] ul.domain_action li.da_edit");
    dmButtons.removeListener('click', this.domainEdit, this);
    dmButtons.on('click', this.domainEdit, this);

    var saveButtons = Ext.select("div[id='" + this.selfId + "'] ul.domain_action li.da_save");
    saveButtons.removeListener('click', this.domainSave, this);
    saveButtons.on('click', this.domainSave, this);

    var deleteButtons = Ext.select("div[id='" + this.selfId + "'] ul.domain_action li.da_delete");
    deleteButtons.removeListener('click', this.domainDelete, this);
    deleteButtons.on('click', this.domainDelete, this);

    //	  var addButtons = Ext.select("div[id='"+this.selfId+"'] ul.domain_action li.da_add");
    //	  addButtons.removeListener('click',this.domainAdd,this);
    //	  addButtons.on('click',this.domainAdd,this);

    var addButton = Ext.select("div[id='" + this.selfId + "'] span.dm_add");
    addButton.removeListener('click', this.domainAdd, this);
    addButton.on('click', this.domainAdd, this);

    var cancelButton = Ext.select("div[id='" + this.selfId + "'] ul.domain_action li.da_edit_cancle");
    cancelButton.removeListener('click', this.editCancle, this);
    cancelButton.on('click', this.editCancle, this);

    var relatedApp = Ext.select("div[id='" + this.selfId + "'] div.relatedApp");
    relatedApp.removeListener('click', this.relateClick, this);
    relatedApp.on('click', this.relateClick, this);

  },
  relateClick: function(e, dom) {
    var thisName = this.appData.title;
    var thatName = dom.title;
    console.log('this:' + thisName);
    console.log("that:" + thatName);
    this.fireEvent('relateClicked', this, thisName, thatName, e);
  },
  domainClick: function(e, dom) {
    var domain = null;
    if (typeof dom.textContent == "string") {
      domain = dom.textContent;
    } else {
      domain = dom.innerText;
    }
    window.open('http://' + domain + "/?q=" + Math.random());
  },
  domainAdd: function(e, dom) {
    if (this.isEditing) {
      return;
    }
    var domainList = Ext.select("div[id='" + this.selfId + "'] ul[data-name='domain']").elements[0];
    var lth = this.appData.domain.length;
    var dlth = this.domainList.length;
    var dmList = '';
    for (var i = 0; i < dlth; i++) {
      dmList += '<option value="' + this.domainList[i] + '">' + this.domainList[i] + '</option>';
    }
    var li = document.createElement("li");
    li.className = 'domain_item clearfix domain_item_edit';
    li.setAttribute("domain-item", lth);
    var html = '<a class="domain_text" target="_blank"></a><div class="domain_edit"> <input type="text" class="domain_front" value=""><select class="domain_back">' + dmList + '</select></div><ul class="add_detail_action domain_action"><li class="icon-pencil3 da_edit" title="编辑" action-name="edit" id="ext-gen1420"></li><li class="icon-cross da_delete" title="删除" action-name="delete"></li><li class="icon-cross da_edit_cancle" title="取消" action-name="delete"></li><li class="icon-checkmark da_save" title="保存" action-name="save"></li></ul>';
    li.innerHTML = html;
    domainList.appendChild(li);
    console.log(html);
    this.isEditing = true;
    this.eventBind();
  },
  domainDelete: function(e, dom) {
    var li = this.getTarNode(dom, 'domain-item');
    var q = parseInt(li.getAttribute('domain-item'));
    var lth = this.appData.domain.length - 1;
    if (q < (lth)) {
      for (var i = q + 1; i <= lth; i++) {
        var tarLi = Ext.select("div[id='" + this.selfId + "'] li[domain-item='" + i + "']").elements[0];
        tarLi.setAttribute('domain-item', i - 1);
      }
    }
    li.remove();
    this.appData.domain.splice(q, 1);
    this.fireEvent('onDomainChange', this, this.appData, 'delete', e);
    this.updateDomainStatus();
  },
  updateDomainStatus: function() {
    var editBlock = Ext.select("div[id='" + this.selfId + "'] li.domain_item_edit");
    var lth = editBlock.elements.length;
    if (lth > 0) {
      this.isEditing = true;
    } else {
      this.isEditing = false;
    }
  },
  domainSave: function(e, dom) {
    var li = this.getTarNode(dom, 'domain-item');
    var q = parseInt(li.getAttribute('domain-item'));
    var text = Ext.select("div[id='" + this.selfId + "'] li[domain-item='" + q + "'] input.domain_front").elements[0];
    var select = Ext.select("div[id='" + this.selfId + "'] li[domain-item='" + q + "'] option:checked").elements[0];
    var name = text.value.trim();
    if (name == '') {
      text.setAttribute('style', 'border-color:#f00');
      setTimeout(function() {
        text.setAttribute('style', 'border-color:#aaa');
      }, 5000);
      return;
    }
    var dm = select.getAttribute('value');
    var display = Ext.select("div[id='" + this.selfId + "'] li[domain-item='" + q + "'] a.domain_text").elements[0];
    display.innerHTML = name + "." + dm;
    //	  var url = 'http://'+name+"." +dm;
    //	  display.setAttribute('href',url);
    var fulDM = name + "." + dm;
    if ((q >= this.appData.domain.length) || (fulDM != this.appData.domain[q])) {
      this.appData.domain[q] = fulDM;
      this.fireEvent('onDomainChange', this, this.appData, 'edit', e);
    }

    li.className = li.className.replace(' domain_item_edit', '');
    this.isEditing = false;


  },
  domainEdit: function(e, dom) {
    var li = this.getTarNode(dom, 'domain-item');
    li.className = li.className + ' domain_item_edit';
    var q = parseInt(li.getAttribute('domain-item'));
    var domain = this.appData.domain[q];
    var dLength = domain.length;
    var name = domain.substring(0, domain.indexOf('.'));
    var dm = domain.substring(domain.indexOf('.') + 1, dLength);
    this.isEditing = true;
  },
  editCancle: function(e, dom) {
    var li = this.getTarNode(dom, 'domain-item');
    if (li.firstChild.innerHTML == '') {
      li.remove();
    } else {
      li.className = li.className.replace(' domain_item_edit', '');
    }
    this.isEditing = false;
  },
  serviceAdd: function(serviceName) {
    var p_service = Ext.select("div[id='" + this.selfId + "'] span[data-name='services']").elements[0];
    var type = serviceName.split('_')[0].toLowerCase();
    var serviceHtml = '<span class="service_sign ' + type + '" title="' + serviceName + '"></span>';


    p_service.innerHTML += serviceHtml;
  },
  appStatusChange: function(e, dom) {
    var actionName = dom.getAttribute('action-name');
    if (actionName == 'loading') {
      return false;
    }
    var ul = this.getTarNode(dom, 'data-name');
    ul.className = 'add_detail_action loading';
    this.fireEvent('onStatusChange', this, actionName, e);
  },
  getValues: function() {
    return this.appData;
  },
  updateAppStatus: function(data) {
    if (!this.appData) {
      this.appData = new Object();
    }
    if (!data) {
      return false;
    } else {
      var img = data.itemImg;
      var title = data.title;
      var message = data.message;
      var itemColor = data.itemColor;
      var status = data.status;
      var instance = data.instance;
      var memory = data.memory;
      var space = data.space / 1024;
      var runtime = data.runtime;
      var service = data.serviceName;
      var instanceStatus = data.instanceStatus;
      var domain = data.domain;
      var relatedApp = data.relatedApp;

      if (img != undefined) {
        var p_img = Ext.select("div[id='" + this.selfId + "'] img[data-name='itemImg']").elements[0];
        p_img.src = img;
        this.appData.itemImg = img;
      }
      if (title != undefined) {
        var p_title = Ext.select("div[id='" + this.selfId + "'] p[data-name='title']").elements[0];
        p_title.innerHTML = title;
        p_title.title = title;
        this.appData.title = title;
      }
      if (message != undefined) {
        var msg = Ext.select("div[id='" + this.selfId + "'] span[data-name='message']");
        var p_message = msg.elements[0];
        p_message.innerHTML = message;
        if (message > 0) {
          msg.show();
        } else {
          msg.hide();
        }
        this.appData.message = message;
      }
      if (itemColor != undefined) {
        var p_itemColor = Ext.select("div[id='" + this.selfId + "'] p.adh_title").elements[0];
        p_itemColor.style.color = itemColor;
        this.appData.itemColor = itemColor;
      }
      if (status != undefined) {
        var p_status = Ext.select("div[id='" + this.selfId + "'] span[data-name='status']").elements[0];
        var p_action = Ext.select("div[id='" + this.selfId + "'] ul[data-name='action_status']").elements[0];
        p_action.className = "add_detail_action " + status;
        p_status.innerHTML = status;
        this.appData.status = status;
      }
      if (instance != undefined) {
        var p_instance = Ext.select("div[id='" + this.selfId + "'] span[data-name='instance']").elements[0];
        p_instance.innerHTML = instance;
        this.appData.instance = instance;
      }
      if (memory != undefined) {
        var p_memory = Ext.select("div[id='" + this.selfId + "'] span[data-name='memory']").elements[0];
        p_memory.innerHTML = memory;
        this.appData.memory = memory;
      }
      if (space) {
        var p_space = Ext.select("div[id='" + this.selfId + "'] span[data-name='space']").elements[0];
        p_space.innerHTML = space;
        this.appData.space = space;
      }
      if (runtime != undefined) {
        var p_runtime = Ext.select("div[id='" + this.selfId + "'] span[data-name='runtime']").elements[0];
        p_runtime.innerHTML = runtime;
        this.appData.runtime = runtime;
      }
      if (service != undefined) {
        if (typeof service == "string") {
          service = service.split(',');
          service = service.slice(0, service.length - 1);
        }
        var p_service = Ext.select("div[id='" + this.selfId + "'] span[data-name='services']").elements[0];
        var lth = service.length;
        this.appData.service = service;
        var serviceHtml = '';
        for (var i = 0; i < lth; i++) {
          var serName = service[i];
          var type = serName.split('_')[0].toLowerCase();
          serviceHtml += '<span class="service_sign ' + type + '" title="' + serName + '"></span>';
        }
        p_service.innerHTML = serviceHtml;
      }
      if (instanceStatus) {
        var total = 0;
        var wNow = 0;
        var zindex = 6;
        var loadingBlock = Ext.select("div[id='" + this.selfId + "'] span.status_loading");
        this.appData.instanceStatus = instanceStatus;
        for (var i in instanceStatus) {
          total += instanceStatus[i];
        }
        for (var i in instanceStatus) {
          wNow += instanceStatus[i];
          var stBar = Ext.select("div[id='" + this.selfId + "'] div[data-name='" + i + "']").elements[0];
          var num = (wNow / total) * 100;
          if (instanceStatus[i] == 0) {
            num = 0;
          }
          var style = 'width:' + num + '%;z-index:' + zindex;
          stBar.setAttribute('style', style);
          //				  stBar.style.width = num+'%';
          //				  stBar.style["z-index"] = zindex;
          zindex--;
          stBar.title = instanceStatus[i] + " " + i;
        }
        loadingBlock.hide();
      }
      if (relatedApp && relatedApp.length > 0) {
        var relatedDom = Ext.select("div[data-name='relatedApp']").elements[0];
        relatedDom.setAttribute('style', 'display:block');
        relatedDom.setAttribute('title', relatedApp);
      }
      if (domain) {
        this.appData.domain = domain;
        if (!this.isEditing) { //判斷是否正在編輯
          var p_domain = Ext.select("div[id='" + this.selfId + "'] ul[data-name='domain']").elements[0];
          lth = data.domain.length;
          console.log(data.domain);
          var domainHtml = '';
          if (lth == 0) {
            p_domain.innerHTML = '';
            return false;
          }
          for (var i = 0; i < lth; i++) {
            var dmText = domain[i];
            var dLength = dmText.length;
            var name = dmText.substring(0, dmText.indexOf('.'));
            var dm = dmText.substring(dmText.indexOf('.') + 1, dLength);
            var domainList = '';
            for (var j = 0; j < this.domainList.length; j++) {
              if (this.domainList[j] == dm) {
                domainList += '<option value="' + this.domainList[j] + '" selected >' + this.domainList[j] + '</option>';
              } else {
                domainList += '<option value="' + this.domainList[j] + '">' + this.domainList[j] + '</option>';
              }

            }
            domainHtml += '<li class="domain_item clearfix" domain-item="' + i + '">' +
              '<a class="domain_text"  target="_blank">' + dmText + '</a>' +
              '<div class="domain_edit">' +
              ' <input type="text" class="domain_front" value="' + name + '" />' +
              '<select class="domain_back" >' +
              domainList +
              '</select>' +
              '</div>' +
              '<ul class="add_detail_action domain_action">' +
              '<li class="icon-pencil3 da_edit" title="' + this.actionList.edit + '" action-name="edit"></li>' +
              //							               '<li class="icon-plus22 da_add" title="'+ this.actionList.add +'" action-name="add"></li>'+
              '<li class="icon-cross da_delete" title="' + this.actionList['delete'] + '" action-name="delete"></li>' +
              '<li class="icon-cross da_edit_cancle" title="' + this.actionList['cancel'] + '" action-name="delete"></li>' +
              '<li class="icon-checkmark da_save" title="' + this.actionList['save'] + '" action-name="save"></li>' +
              '</ul>' +
              '</li>';
          }
          p_domain.innerHTML = domainHtml;
        }

      }
    }
    this.eventBind();
  },
  htmlInit: function() {
    var detail = '<div class="add_detail_left">' +
      '<dl class="add_detail_items">' +
      '<dt>' + this.detailList[0] + '：</dt>' +
      '<dd>' +
      '<span class="running_status" data-name="status"></span>' +
      '<ul class="add_detail_action"  data-name="action_status">' +
      '<li class="loading ada_loading" action-name="loading" title="' + this.actionList['loading'] + '"></li>' +
      '<li class="icon-play3 aa_start ada_start" action-name="start"  title="' + this.actionList['start'] + '"></li>' +
      '<li class="icon-rotate2 ada_restart" action-name="restart" title="' + this.actionList['restart'] + '"></li>' +
      '<li class="icon-stop ada_stop" action-name="stop" title="' + this.actionList['stop'] + '"></li>' +
      '</ul>' +
      ' </dd>' +
      '</dl>' +
      '<dl class="add_detail_items">' +
      '<dt>' + this.detailList[1] + '：</dt>' +
      '<dd><span data-name="instance"></span></dd>' +
      '</dl>' +
      '<dl class="add_detail_items">' +
      '<dt>' + this.detailList[2] + '：</dt>' +
      '<dd><span data-name="memory"></span>G/<span data-name="space"></span>G</dd>' +
      '</dl>' +
      '<dl class="add_detail_items">' +
      '<dt>' + this.detailList[3] + '：</dt>' +
      '<dd><span data-name="runtime"></span></dd>' +
      '</dl>' +
      '<dl class="add_detail_items">' +
      '<dt>' + this.detailList[4] + '：</dt>' +
      '<dd><span data-name="services" class="adi_service"></span></dd>' +
      '</dl>' +
      '</div>' +
      '<div class="add_detail_right">' +
      '<dl class="add_detail_items">' +
      '<dt>' + this.detailList[5] + '：</dt>' +
      '<dd><span class="loading_block status_loading" style="float:left"></span>' +
      '<div class="instance_status" data-name="instance_status">' +
      '<div class="status_bar status_bar_1" style="z-index:10" data-name="DOWN" title="3errors"></div>' +
      '<div class="status_bar status_bar_2" style="z-index:9" data-name="STARTING" title="2warnings"></div>' +
      '<div class="status_bar status_bar_3" style="z-index:8" data-name="RUNNING"></div>' +
      '<div class="status_bar status_bar_4" style="z-index:7" data-name="CRASHED"></div>' +
      '<div class="status_bar status_bar_5" style="z-index:6" data-name="FLAPPING"></div>' +
      '<div class="status_bar status_bar_6" style="z-index:5" data-name="UNKNOWN"></div>' +
      '</div>' +
      '</dd>' +
      '</dl>' +
      '<dl class="add_detail_items ai_domain">' +
      '<dt>' + this.detailList[6] + '：</dt>' +
      '<dd class="domainBlock">' +
      '<ul data-name="domain">' +
      '<span class="loading_block pos_a"></span>' +
      ' </ul>' +
      '<span class="dm_add icon-plus22"></span>' +
      '</dd>' +
      '</dl>' +
      ' </div>';

    this.html = this.htmlTemp + detail + this.htmlTemp2;
  },
  getTarNode: function(tar, tag) {
    if (tar.tagName == undefined) {
      return false;
    }
    var res = tar.getAttribute(tag);
    if (res != null && res.length > 0) {
      return tar;
    } else {
      return this.getTarNode(tar.parentNode, tag);
    }
  }
});
